package com.example.forum.services.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleReplyMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.ArticleReply;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleServices;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private IArticleServices articleServices;

    @Override
    public int create(ArticleReply articleReply) {
        //参数校验
        if (articleReply == null ||
                articleReply.getArticleId() == null ||
                articleReply.getContent().trim().equals("")) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);

        //写入数据库
        Integer result = articleReplyMapper.insertSelective(articleReply);
        if (result == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        //更新文章表中的帖子的回复数
        if (articleServices.addOneReplyCountById(articleReply.getArticleId()) == 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
            log.error(e.getStackTrace().toString());
            throw e;
        }

        log.info("回复成功 articleId = " + articleReply.getArticleId() + "userId = " + articleReply.getPostUserId());
        return result;
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if (articleId == null || articleId <= 0) {
            ApplicationException e = new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
            log.error(e.getStackTrace().toString());
            throw e;
        }
        //调用dao 查询回复列表
        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);
        return result;
    }
}
